<template>
  <div class="forget-password-container" @click="showDisclaimerDialog">
    <div class="forget-password-box" @click.stop>
      <div class="forget-password-form-container">
        <div class="forget-password-form">
          <div class="form-header">
            <h2>找回密码</h2>
            <el-button link icon="ArrowLeft" @click="goToLogin">返回登录</el-button>
          </div>

          <!-- 步骤指示器 -->
          <el-steps :active="currentStep" finish-status="success" simple class="steps-inline">
            <el-step title="输入邮箱" />
            <el-step title="输入验证码" />
            <el-step title="重置密码" />
          </el-steps>

          <el-form ref="forgetPassFormRef" :model="forgetPassForm" :rules="rules" label-width="0" @keyup.enter="handleSubmit" @submit.prevent>
            <!-- 步骤1：验证邮箱 -->
            <template v-if="currentStep === 1">
              <el-form-item prop="email">
                <el-input
                    v-model="forgetPassForm.email"
                    placeholder="请输入您的邮箱"
                    prefix-icon="Message"
                    @compositionstart="inputComposing = true"
                    @compositionend="inputComposing = false"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <div class="buttons-container single-button">
                  <el-button
                    type="primary"
                    class="submit-button"
                    :loading="loading"
                    @click="handleSubmit"
                  >
                    下一步
                  </el-button>
                </div>
              </el-form-item>
            </template>

            <!-- 步骤2：验证邮箱验证码 -->
            <template v-if="currentStep === 2">
              <el-alert
                type="info"
                show-icon
                :closable="false"
                :title="`邮箱：${forgetPassForm.email}`"
              >
                <template #description>
                  <p>我们已向您的邮箱发送了验证码，请查收并填写</p>
                </template>
              </el-alert>
              
              <el-form-item prop="code" class="mt-4" style="width: 100%">
                <div class="email-code-container">
                  <el-input
                    v-model="forgetPassForm.code"
                    placeholder="请输入邮箱验证码"
                    prefix-icon="Key"
                    @compositionstart="inputComposing = true"
                    @compositionend="inputComposing = false"
                  ></el-input>
                  <el-button
                    type="primary"
                    plain
                    class="send-code-btn"
                    :loading="loading"
                    @click="sendEmailCode"
                  >
                    重新发送
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item>
                <div class="buttons-container">
                  <el-button
                    type="default"
                    class="back-button"
                    @click="goToPreviousStep"
                  >
                    返回上一步
                  </el-button>
                  <el-button
                    type="primary"
                    class="submit-button"
                    :loading="loading"
                    @click="handleSubmit"
                  >
                    下一步
                  </el-button>
                </div>
              </el-form-item>
            </template>

            <!-- 步骤3：重置密码 -->
            <template v-if="currentStep === 3">
              <el-alert
                type="info"
                show-icon
                :closable="false"
                :title="`邮箱：${forgetPassForm.email}`"
              >
                <template #description>
                  <p>请设置新密码</p>
                </template>
              </el-alert>

              <el-form-item prop="password" class="mt-4">
                <el-input
                    v-model="forgetPassForm.password"
                    type="password"
                    placeholder="请输入新密码"
                    prefix-icon="Lock"
                    show-password
                    @compositionstart="inputComposing = true"
                    @compositionend="inputComposing = false"
                ></el-input>
              </el-form-item>
              <el-form-item prop="confirmPassword">
                <el-input
                    v-model="forgetPassForm.confirmPassword"
                    type="password"
                    placeholder="请确认新密码"
                    prefix-icon="Lock"
                    show-password
                    @compositionstart="inputComposing = true"
                    @compositionend="inputComposing = false"
                ></el-input>
              </el-form-item>
              <div class="password-tips">
                <p>密码要求：6-15位，必须包含数字、字母和特殊字符(@、#、_、~)</p>
              </div>
              <el-form-item>
                <div class="buttons-container">
                  <el-button
                    type="default"
                    class="back-button"
                    @click="goToPreviousStep"
                  >
                    返回上一步
                  </el-button>
                  <el-button
                    type="primary"
                    class="submit-button"
                    :loading="loading"
                    @click="handleSubmit"
                  >
                    重置密码
                  </el-button>
                </div>
              </el-form-item>
            </template>
          </el-form>

          <div class="login-link">
            想起密码了？<a href="javascript:;" @click="goToLogin">立即登录</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import {
  ForgetPassCaptchaAPI,
  editPasswordAPI
} from '../api/auth';
import { 
  showSuccess, 
  showWarning, 
  showError 
} from '../components/layout/GlobalNotification.vue';
import { showDisclaimer } from '../components/layout/GlobalNotification.vue';

const router = useRouter();
const loading = ref(false);
const forgetPassFormRef = ref();
const inputComposing = ref(false); // 是否正在输入中文

// 当前步骤
const currentStep = ref(1); // 始终从第一步开始

// 表单数据
const forgetPassForm = reactive({
  email: '',
  code: '', // 验证码
  captchaId: '', // 存储验证码ID
  password: '',
  confirmPassword: ''
});

// 组件挂载时重置表单
onMounted(() => {
  // 确保表单重置
  resetForm();
  // 确保从第一步开始
  currentStep.value = 1;
});

// 验证规则
const validateEmail = (rule: any, value: string, callback: (error?: Error) => void) => {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!value) {
    callback(new Error('请输入邮箱地址'));
  } else if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'));
  } else {
    callback();
  }
};

const validatePassword = (rule: any, value: string, callback: (error?: Error) => void) => {
  // 密码强度规则：6-15位，必须包含数字和字母，必须包含特殊字符(@、#、_、~)
  const passwordRegex = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[@#_~])[\w@#_~]{6,15}$/;
  if (!value) {
    callback(new Error('请输入密码'));
  } else if (!passwordRegex.test(value)) {
    callback(new Error('密码格式不符合要求，请包含数字、字母和特殊字符(@#_~)'));
  } else {
    callback();
  }
};

const validateConfirmPassword = (rule: any, value: string, callback: (error?: Error) => void) => {
  if (!value) {
    callback(new Error('请确认密码'));
  } else if (value !== forgetPassForm.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

// 按步骤定义验证规则
const rules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入邮箱验证码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
};

// 1、发送邮箱验证码
const sendEmailCode = async () => {
  try {
    // 先验证邮箱格式
    await forgetPassFormRef.value.validateField('email');
    loading.value = true;
    
    // 确保验证码字段为空
    forgetPassForm.code = '';
    
    // 调用发送邮箱验证码的API
    const res = await ForgetPassCaptchaAPI(forgetPassForm.email);
    
    if (res.code === 200) {
      // 保存captchaId
      forgetPassForm.captchaId = res.captchaId || '';
      showSuccess('验证码已发送到您的邮箱，请注意查收');
      // 进入第二步
      currentStep.value = 2;
    } else {
      showError(res.msg || '发送验证码失败，请重试');
    }
  } catch (error) {
    console.error('验证或发送邮箱验证码错误:', error);
    // 这里不需要特别处理，因为验证失败会由Element Plus表单自动显示错误信息
  } finally {
    loading.value = false;
  }
};

// 2、填写邮箱验证码，进入设置密码步骤
const verifyEmailCode = async () => {
  try {
    // 验证验证码字段
    await forgetPassFormRef.value.validateField('code');
    // 验证通过，直接进入第三步
    currentStep.value = 3;
  } catch (error) {
    console.error('验证码验证错误:', error);
    // 验证失败会由Element Plus表单自动显示错误信息
  }
};

// 提交修改密码
const submitPasswordChange = async () => {
  if (inputComposing.value) return;
  
  forgetPassFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        loading.value = true;
        
        // 调用修改密码的API
        const response = await editPasswordAPI({
          email: forgetPassForm.email,
          password: forgetPassForm.password,
          confirmPassword: forgetPassForm.confirmPassword,
          captchaId: forgetPassForm.captchaId,
          code: forgetPassForm.code
        });
        
        if (response.code === 200) {
          showSuccess('密码修改成功，请使用新密码登录');
          setTimeout(() => {
            router.push('/login');
          }, 1500);
        } else {
          showError(response.msg || '密码修改失败，请重试');
          // 出错时直接返回第一步
          resetForm();
          currentStep.value = 1;
        }
      } catch (error) {
        console.error('密码修改错误:', error);
        showError('密码修改失败，请重试');
        // 出错时直接返回第一步
        resetForm();
        currentStep.value = 1;
      } finally {
        loading.value = false;
      }
    } else {
      showWarning('请按要求填写所有信息');
    }
  });
};

// 重置表单
const resetForm = () => {
  // 清除验证状态
  forgetPassFormRef.value?.clearValidate();
  // 重置所有字段
  forgetPassForm.email = '';
  forgetPassForm.code = '';
  forgetPassForm.captchaId = '';
  forgetPassForm.password = '';
  forgetPassForm.confirmPassword = '';
};

// 表单的submit处理，根据当前步骤调用不同的处理函数
const handleSubmit = () => {
  if (currentStep.value === 1) {
    sendEmailCode();
  } else if (currentStep.value === 2) {
    verifyEmailCode();
  } else if (currentStep.value === 3) {
    submitPasswordChange();
  }
};

// 返回登录页
const goToLogin = () => {
  router.push('/login');
};

// 返回上一步
const goToPreviousStep = () => {
  if (currentStep.value > 1) {
    // 当返回上一步时，清除当前表单字段的验证错误
    if (currentStep.value === 2) {
      forgetPassFormRef.value?.clearValidate('code');
    } else if (currentStep.value === 3) {
      forgetPassFormRef.value?.clearValidate(['password', 'confirmPassword']);
    }
    
    // 减少步骤
    currentStep.value--;
  }
};

// 显示免责声明对话框
const showDisclaimerDialog = () => {
  showDisclaimer();
};
</script>

<style scoped>
.forget-password-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('../assets/images/xiaomi3.png');
  background-size: cover;
  background-position: center;
  position: relative;
  cursor: pointer;
}

.forget-password-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(0,0,0,0.2) 0%, rgba(0,0,0,0.1) 100%);
  z-index: 1;
}

.forget-password-box {
  width: 580px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  position: relative;
  z-index: 10;
  background-image: none;
  cursor: default;
}

.forget-password-form-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 45px 50px;
}

.forget-password-form {
  width: 100%;
  max-width: 480px;
  margin: 0 auto;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 42px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 18px;
}

.form-header h2 {
  font-size: 26px;
  font-weight: 600;
  margin: 0;
  background: linear-gradient(90deg, var(--el-color-primary), #67c23a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  position: relative;
}

.form-header h2::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -18px;
  height: 3px;
  width: 40px;
  background: linear-gradient(90deg, var(--el-color-primary), #67c23a);
  border-radius: 3px;
}

/* 使步骤条在一行内显示 */
.steps-inline {
  display: flex;
  justify-content: space-between;
  margin-bottom: 42px;
  padding: 5px 10px;
  border-radius: 12px;
  background-color: rgba(var(--el-color-primary-rgb), 0.05);
}

:deep(.steps-inline .el-step) {
  flex-basis: 33.33%;
  padding: 0;
}

:deep(.steps-inline .el-step__title) {
  font-size: 13px;
  font-weight: normal;
  white-space: nowrap;
  text-overflow: ellipsis;
  max-width: 100%;
  display: block;
  padding: 0;
  line-height: 1.4;
}

:deep(.steps-inline .el-step__main) {
  display: block;
  text-align: center;
  padding: 0;
}

:deep(.steps-inline .el-step__line) {
  top: 15px;
}

:deep(.steps-inline .el-step__icon.is-text) {
  border: 2px solid;
  font-weight: bold;
}

/* 当前步骤样式 */
:deep(.steps-inline .el-step.is-process .el-step__icon.is-text) {
  background: linear-gradient(90deg, var(--el-color-primary), #67c23a);
  border: none;
}

:deep(.steps-inline .el-step.is-process .el-step__title) {
  font-weight: bold;
  color: var(--el-color-primary);
}

/* 未到达的步骤样式 */
:deep(.steps-inline .el-step.is-wait .el-step__title) {
  color: #909399;
}

:deep(.steps-inline .el-step.is-wait .el-step__icon.is-text) {
  border-color: #c0c4cc;
  color: #c0c4cc;
}

:deep(.steps-inline .el-step.is-wait .el-step__line) {
  background-color: #e4e7ed;
}

.email-display {
  background-color: rgba(var(--el-color-info-rgb), 0.08);
  padding: 16px 20px;
  border-radius: 10px;
  margin-bottom: 28px;
  display: flex;
  align-items: center;
  box-shadow: inset 0 0 0 1px rgba(var(--el-color-info-rgb), 0.1);
}

.email-display .label {
  font-weight: 600;
  margin-right: 10px;
  color: var(--el-text-color-primary);
}

.email-display .value {
  color: var(--el-text-color-regular);
  word-break: break-all;
}

.captcha-container {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-bottom: 10px;
}

.captcha-container .el-input {
  flex: 1;
  min-width: 0;
}

.captcha-wrapper {
  width: 110px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.captcha-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}

.captcha-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.loading-icon {
  animation: rotating 2s linear infinite;
}

.email-code-container {
  display: flex;
  gap: 14px;
  align-items: center;
  width: 100%;
}

.email-code-container .el-input {
  flex: 1;
}

.send-code-btn {
  white-space: nowrap;
  min-width: 100px;
  height: 44px;
  border-radius: 8px;
  transition: all 0.3s;
}

.send-code-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 3px 8px rgba(var(--el-color-primary-rgb), 0.2);
}

.submit-button {
  width: 100%;
  max-width: 300px;
  margin: 20px auto 10px;
  height: 46px;
  font-size: 16px;
  border-radius: 10px;
  background: linear-gradient(90deg, var(--el-color-primary), #67c23a);
  border: none;
  display: block;
  transition: all 0.3s;
  box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.2);
}

.submit-button:hover {
  background: linear-gradient(90deg, #66b1ff, #85ce61);
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(var(--el-color-primary-rgb), 0.3);
}

.login-link {
  text-align: center;
  margin-top: 35px;
  color: var(--el-text-color-regular);
  position: relative;
}

.login-link::before, .login-link::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 80px;
  height: 1px;
  background-color: rgba(0,0,0,0.1);
}

.login-link::before {
  left: 60px;
}

.login-link::after {
  right: 60px;
}

.login-link a {
  color: var(--el-color-primary);
  text-decoration: none;
  font-weight: 600;
  transition: color 0.3s;
}

.login-link a:hover {
  color: #67c23a;
  text-decoration: underline;
}

.email-notice {
  background-color: rgba(var(--el-color-primary-rgb), 0.08);
  border-radius: 10px;
  padding: 16px 20px;
  margin-bottom: 28px;
  box-shadow: inset 0 0 0 1px rgba(var(--el-color-primary-rgb), 0.1);
  position: relative;
  overflow: hidden;
}

.email-notice::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(to bottom, var(--el-color-primary), #67c23a);
  border-radius: 4px 0 0 4px;
}

.email-notice p {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.password-tips {
  margin: 8px 0 24px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  padding-left: 2px;
  position: relative;
  padding-left: 20px;
}

.password-tips::before {
  content: "※";
  position: absolute;
  left: 0;
  top: 0;
  color: #e6a23c;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

:deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  max-width: 100%;
  transition: all 0.3s;
  box-shadow: 0 0 0 1px var(--el-border-color) inset;
  padding: 0 15px;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

:deep(.el-input__inner) {
  height: 44px;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-color-danger) inset;
}

:deep(.el-button) {
  font-weight: 600;
}

:deep(.el-form-item__error) {
  padding-top: 4px;
  color: #f56c6c;
}

/* 新增的间距样式 */
.mt-4 {
  margin-top: 1rem;
}

/* 确保表单项占据全宽 */
:deep(.el-form-item__content) {
  width: 100%;
}

.buttons-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  max-width: 300px;
  margin: 20px auto 10px;
  gap: 15px;
}

.back-button {
  flex: 1;
  background-color: rgba(var(--el-color-primary-rgb), 0.08);
  border: none;
  height: 46px;
  border-radius: 10px;
  transition: all 0.3s;
}

.back-button:hover {
  background-color: rgba(var(--el-color-primary-rgb), 0.15);
  transform: translateY(-2px);
}

.submit-button {
  flex: 2;
  margin: 0;
}

.single-button {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>